package mspbots.qbd.common;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.StringUtils;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * mspbots.data.cw.Page
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/8/19
 */
public class QueryParams extends LinkedMultiValueMap<String, String> {

    @Min(0)
    private int page;

    @Min(0)
    @Max(500)
    private int pageSize;

    private String query;

    /**
     * Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}.
     */
    public QueryParams() {
        super(new LinkedHashMap<>());
    }

    /**
     * Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}
     * with the given initial capacity.
     *
     * @param initialCapacity the initial capacity
     */
    public QueryParams(int initialCapacity) {
        super(new LinkedHashMap<>(initialCapacity));
    }

    /**
     * Copy constructor: Create a new LinkedMultiValueMap with the same mappings as
     * the specified Map. Note that this will be a shallow copy; its value-holding
     * List entries will get reused and therefore cannot get modified independently.
     *
     * @param otherMap the Map whose mappings are to be placed in this Map
     * @see #clone()
     * @see #deepCopy()
     */
    public QueryParams(Map<String, List<String>> otherMap) {
        super(new LinkedHashMap<>(otherMap));
    }

    /**
     * default query params
     * max records 500
     * page 0
     *
     * @return default query body
     */
    public static QueryParams withDefault(String query) {
        QueryParams queryParams = new QueryParams(8);
        return queryParams.setQuery(query).setPage(0).setPageSize(500);
    }

    /**
     * default query params
     * max records 500
     * page 0
     *
     * @return default query body
     */
    public static QueryParams withCount(String query) {
        QueryParams queryParams = new QueryParams(8);
        return queryParams.setQuery(query).setPage(0).setPageSize(0);
    }

    public int getPage() {
        return page;
    }

    public QueryParams setPage(int page) {
        this.page = page;
        return this;
    }

    public int getPageSize() {
        return pageSize;
    }

    public QueryParams setPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }

    public String getQuery() {
        if (StringUtils.isEmpty(this.query)) {
            return null;
        }

        if (this.pageSize > 0) {
            return this.query + " STARTPOSITION " + (this.page * this.pageSize + 1) + " MAXRESULTS " + this.pageSize;
        }

        return this.query;
    }

    public QueryParams setQuery(String query) {
        this.query = query;
        return this;
    }

}
